#include <iostream>
#include <memory>
#include <string>

#include <opencv2/opencv.hpp>
#include <opencv2/imgcodecs/legacy/constants_c.h>
#include <grpcpp/grpcpp.h>
#include <grpcpp/health_check_service_interface.h>
#include <grpcpp/ext/proto_server_reflection_plugin.h>

#include "image.grpc.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using rcimage::ImageRequest;
using rcimage::CenterReply;
using rcimage::RcRpcServer;

class GreeterServiceImpl final : public RcRpcServer::Service {
    Status Center(ServerContext* context, const ImageRequest* imageRequest,
               CenterReply* centerReply) override {
        ;
        std::string image_str=imageRequest->image();
        std::vector<uchar> image_data(image_str.begin(),image_str.end());
        cv::Mat recive_image=cv::imdecode(image_data,CV_LOAD_IMAGE_COLOR);
        cv::imwrite("server.jpg",recive_image);
        centerReply->set_result(1);
        return Status::OK;
    }
};

void RunServer() {
    std::string server_address("localhost:50051");
    GreeterServiceImpl service;

    grpc::EnableDefaultHealthCheckService(true);
    grpc::reflection::InitProtoReflectionServerBuilderPlugin();
    ServerBuilder builder;
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    builder.RegisterService(&service);
    std::unique_ptr<Server> server(builder.BuildAndStart());
    std::cout << "Server listening on " << server_address << std::endl;

    server->Wait();
}

int main(int argc, char** argv) {
    RunServer();

    return 0;
}
